package com.coincalf.exchange.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.coincalf.exchange.entity.EntrustOrder;
import com.coincalf.exchange.mapper.EntrustOrderMapper;
import com.coincalf.exchange.service.EntrustOrderService;
import com.coincalf.framework.enums.OrderStatus;
import com.coincalf.framework.enums.OrderType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 委托订单信息 服务实现类
 * </p>
 *
 * @author qiang
 * @since 2018-05-12
 */
@Service
public class EntrustOrderServiceImpl extends ServiceImpl<EntrustOrderMapper, EntrustOrder> implements EntrustOrderService {

    /**
     * 插叙能与之撮合的委托订单
     *
     * @param marketId  交易对ID
     * @param orderType 委托订单类型
     * @param price     委托价格
     * @return
     */
    @Override
    public List<EntrustOrder> queryMatchEntrustOrder(Long marketId, OrderType orderType, BigDecimal price) {
        EntityWrapper<EntrustOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("market_id", marketId)
                .eq("type", orderType.getCode())
                .eq("status", OrderStatus.PENDING.getCode());
        if (orderType == OrderType.BUY) {
            wrapper.ge("price", price);
            wrapper.orderBy("price", false);
        } else {
            wrapper.le("price", price);
            wrapper.orderBy("price", true);
        }
        wrapper.orderBy("created", true);
        wrapper.last("LIMIT 1000");
        return baseMapper.selectList(wrapper);
    }

    /**
     * 修改币币交易委托订单
     *
     * @param orderId            委托订单号
     * @param lockAmount         冻结金额
     * @param dealVolume         当前成交量
     * @param entrustOrderStatus 委托订单状态
     */
    @Override
    public int modifyTradeEntrustOrder(long orderId, BigDecimal lockAmount, BigDecimal dealVolume, OrderStatus entrustOrderStatus) {
        return baseMapper.modifyTradeEntrustOrder(orderId, lockAmount, dealVolume, entrustOrderStatus.getCode());
    }

    /**
     * 将委托订单状态修改为已成交
     *
     * @param orderId 订单号
     * @return
     */
    @Override
    @Transactional
    public int modifyTradeEntrustOrderToDeal(long orderId) {
        return baseMapper.modifyTradeEntrustOrderToDeal(orderId);
    }

    /**
     * 修改占用保证金
     *
     * @param orderId    订单号
     * @param lockMargin 占用保证金
     * @return
     */
    @Override
    public int modifyLockMargin(long orderId, BigDecimal lockMargin) {
        return baseMapper.modifyLockMargin(orderId, lockMargin);
    }
}
